package org.xelnaga.defiler.web.controller.contentlet;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.xelnaga.defiler.domain.ContentletModel;
import org.xelnaga.defiler.domain.FieldModel;
import org.xelnaga.defiler.domain.FolderModel;
import org.xelnaga.defiler.domain.StructureModel;
import org.xelnaga.defiler.service.ContentletService;
import org.xelnaga.defiler.service.FolderService;
import org.xelnaga.defiler.service.StructureService;

/**
 * Default implementation of ContentletFormService
 */
@Service
public class ContentletFormService {
    @Autowired
    private ContentletService contentletManager;
    @Autowired
    private StructureService structureService;
    @Autowired
    private FolderService folderService;
    /**
     * When the passed contentletForm holds a contentlet that contains enough information 
     * (primary key or unique field), it retrieves the corresponding contentlet data from
     * the repository (eg database) and fill the contentletForm with the retrieved data.
     * It is used to prefill an update form or to prefill the form before setting properties 
     * sent by the User agent.
     * 
     * @return the same form, eventually filled with deshydrated data retrieved from the repository.
     */
	public ContentletForm populateForm(ContentletForm contentletForm) {
		Long contentletInode = contentletForm.getContentlet().getInode();
        ContentletModel contentlet = contentletManager.getByPrimaryKey(contentletInode);
        if (contentlet != null) {
            // update form with a disconnected version of contentlet
        	contentletForm.setContentlet(contentlet);
        } else {
        	Long structureInode = contentletForm.getContentlet().getStructureInode();
        	contentletForm.getContentlet().setStructure(structureService.getByPrimaryKey(structureInode));
        }
        return contentletForm;
	}

    /**
     * Create a new persistent ContentletModel using the deshydraded 
     * information passed in the contentletForm.
     * @param categoriesValue 
     * @param fileAssetModel 
     * 
     * @return the newly created ContentletModel instance.
     */ 	
	 public ContentletModel create(ContentletForm contentletForm, Map<FieldModel, String[]> categoriesValue) {
		 ContentletModel created = contentletForm.getContentlet();
		 for(Map.Entry<FieldModel, String[]> entry : categoriesValue.entrySet()) {
			 if(null != entry.getValue() && entry.getValue().length > 0) {
				 created.setFieldValue(entry.getKey().getFieldContentlet(), StringUtils.join(entry.getValue(), ","));
			 }
		 }
		 Long folderInode = contentletForm.getContentlet().getFolderInode();
		 if(null != folderInode) {
			 created.setFolder(folderService.getByPrimaryKey(folderInode));
		 }
		 
		 Long structureInode = contentletForm.getContentlet().getStructureInode();
		 StructureModel structure = structureService.getByPrimaryKey(structureInode);
		 created.setStructure(structure);
		 
		 //Setting review intervals form properties
		 if(structure.getReviewInterval() != null) {
			 String interval = structure.getReviewInterval();
			 created.setReviewInterval(interval);
			 // saving the review dates
			 created.setLastReview(new Date ());
			 if(created.getReviewInterval() != null) {
				 created.setNextReview(getNextReview(created, false));
			 }
		 }
		 
		 String imgPath = "/" + FolderModel.SystemFolderEnum.Img.name().toLowerCase() + "/" + structure.getVelocityVarName();
		 FolderModel parentFolder = folderService.getBySiteAndPath(created.getFolder().getSiteInode(), imgPath);
		 if(null != created.getFileAsset()) {
			 created.getFileAsset().setParentNode(parentFolder);
			 created.getFileAsset().setSite(parentFolder.getSite());
		 }
		 if(null != created.getIconFileAsset()) {
			 created.getIconFileAsset().setParentNode(parentFolder);
			 created.getIconFileAsset().setSite(parentFolder.getSite());
		 }
		 this.contentletManager.save(created);
		 return created;
	 }
	 
	 public Date getNextReview(ContentletModel content, boolean respectFrontendRoles) {
		 Date baseDate = new Date();
		 String reviewInterval = content.getReviewInterval();
		 Pattern p = Pattern.compile("(\\d+)([dmy])");
		 Matcher m = p.matcher(reviewInterval);
		 boolean b = m.matches();
		 GregorianCalendar cal = new GregorianCalendar();
		 cal.setTime(baseDate);
		 if (b) {
			 int num = Integer.parseInt(m.group(1));
			 String qual = m.group(2);
			 if(qual.equals("d")) {
				 cal.add(GregorianCalendar.DATE, num);
			 }	
			 if(qual.equals("m")) {
				 cal.add(GregorianCalendar.MONTH, num);
			 }
			 if(qual.equals("y")) {
				 cal.add(GregorianCalendar.YEAR, num);
			 }
		 }
		 return cal.getTime();
	 }
}